#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#define LEN 128
#define ERROR_CHECK(ret, num, msg) \
    {                              \
        if (ret == num)            \
        {                          \
            perror(msg);           \
            exit(1);               \
        }                          \
    }
void myGetTime(char **time_str, int line)
{
    setenv("TZ", "Asia/Shanghai", 1);
    tzset(); // 通知C库时区已更改
    // 获取当前时间
    time_t rawtime;
    time(&rawtime);
    struct tm *timeinfo = localtime(&rawtime);
    // 分配内存并格式化时间字符串
    *time_str = malloc(LEN); // 分配足够的内存
    if (*time_str == NULL)
    {
        perror("malloc");
        exit(1);
    }
    snprintf(*time_str, LEN,
             "%d,%04d-%02d-%02d-%02d:%02d:%02d\n",
             line,
             timeinfo->tm_year + 1900,
             timeinfo->tm_mon + 1,
             timeinfo->tm_mday,
             timeinfo->tm_hour,
             timeinfo->tm_min,
             timeinfo->tm_sec);
}

int main(int argc, char *argv[])
{
    FILE *fp = fopen("datetest.txt", "a+");
    ERROR_CHECK(NULL, fp, "fopen");
    char *time_str = NULL;
    char *p = ",";
    char *word = NULL;
    int line = 1;
    char buf[64] = {0};
    int num = 0;
    while (1)
    {
        if (EOF != fgetc(fp))
        {
            puts("---");
            while (fgets(buf, sizeof(buf), fp))
                ;
            word = strtok(buf, p);
            line = atoi(word) + 1;
        }
        myGetTime(&time_str, line);
        puts(time_str);
        line++;
        fwrite(time_str, 1, strlen(time_str), fp);
        fflush(fp); // 刷新文件缓冲区到磁盘

        free(time_str);
        sleep(1);
    }

    fclose(fp);
    free(time_str);
    return 0;
}